#!/usr/bin/python

# This script reads a CUE sheet, and embeds the metadata into the associated 
# flac file as flac tags, in a format that is readable by slimserver. Album 
# art is also embedded, if found. 
# 

# TODO: Make class, accept either CUE object, CUE sheet text, or path to CUE

import os, sys
from tkFileDialog import askopenfilename, askdirectory
import tkMessageBox
from CueParser import CueParser

if len(sys.argv) > 1:
  cuefilename = sys.argv[1]
else:
  cuefilename = askopenfilename(title='Select CUE Sheet',filetypes=(('CUE Sheets', '*.cue'),("All Files", "*")))

# TODO: utf8
try:
  import codecs
  fin = codecs.open(cuefilename, "r", "utf8")
  cuefile = fin.read()
finally:
  fin.close()

cue = CueParser()
filepath = os.path.dirname(cuefilename)
soundfile = os.path.join(filepath,cue.getSoundFileFromCue(cuefile))
tagfile = os.path.join(filepath,'tags.txt')
basename = os.path.splitext(os.path.basename(cuefilename))[0]

thissamples = int(os.popen("metaflac --show-total-samples \"" + soundfile + "\" --").read().strip())
thissr = int(os.popen("metaflac --show-total-samples \"" + soundfile + "\" --").read().strip())

cue.getMetadataFromCue(cuefile,thissamples,thissr)

argstring = "metaflac --import-cuesheet-from=\"" + cuefilename + "\" --import-tags-from=\"" + tagfile + "\""

if os.path.exists(os.path.join(filepath,basename+".jpg")):
  argstring += " --import-picture-from=\"" + os.path.join(filepath,basename+".jpg") + "\""

tags = "ARTIST=" + cue.performer + "\n"
tags = tags + "ALBUM=" + cue.title + "\n"
tags = tags + "YEAR=" + cue.year + "\n"

for track in cue.tracks:
  tags = tags + "TITLE[" + str(track.number) + "]=" + track.name + "\n"
  tags = tags + "ARTIST[" + str(track.number) + "]=" + track.performer + "\n"
  tags = tags + "TRACKNUMBER[" + str(track.number) + "]=" + str(track.number) + "\n"
  
for remark in cue.remarks:
  tags = tags + "REMARK=" + remark.key + "=" + remark.val + "\n"

f=open(tagfile, 'w')
f.write(tags)
f.close()

argstring = argstring + " \"" + soundfile + "\""
clearstring = "metaflac --remove-all \"" + soundfile + "\""

ret = os.popen(clearstring).read().strip()
ret = os.popen(argstring).read().strip()
print ret
